#include "baseLang.h"

#include <filesystem>
#include <iostream>
#include <string>
#include "../utility/type_traits.hpp"

namespace fs = std::filesystem;

Language::Language(const std::string& name) : name(name) {
    Log::instance().getOutput() << "register langMap: " << name << std::endl;
    langMap.emplace(name, this);
}

std::string Language::detect(const std::string& src, const std::string& dstPath) const {
    if (suffix == "") {
        return (fs::path(dstPath) / fs::path(src).filename()).string();
    }
    return fs::path(dstPath).append(fs::path(src).stem().string() + "." + suffix).string();
}

std::string Language::getBinaryFilename(std::string src) const {
    int x = src.rfind('.');
        if (x == -1) {
            return src + ".out";
        }
    return src.substr(0, x + 1) + "out";
}

std::string Language::prepare(const std::string& src, const std::string& dst) const {
    auto target_path = fs::path(dst).parent_path();
    std::error_code err;
    fs::create_directories(target_path, err);
    if (err) {
        Log::instance().getOutput() << "create directory error:" << err.message() << std::endl;
        return "";
    }
    fs::copy(src, dst, fs::copy_options::overwrite_existing, err);
    if (err && err != std::errc::file_exists) {
        Log::instance().getOutput() << "copy file error:" << err.message() << std::endl;
        return "";
    }
    return dst;
}
// 若target为空，则将在filename下直接编译，返回当前语言的编译命令
std::string Language::compileFileStr(std::string filename, std::string target) const { return ""; }
// 当前语言编译出的可执行文件的执行命令
std::string Language::runFileStr(std::string filename) const {
        std::string command = filename;
        if (command.find("./") != 0 && command.size() && command[0] != '/')
            command = "./" + command;
        return command + run_option;
}


std::unordered_map<std::string, const Language*> langMap = {};
std::unordered_map<std::string, std::string> suffixMap = {};


const Language* DEFAULT_LANG = new Language{};